package com.FTW.SAA.config;

import cn.hutool.crypto.digest.DigestUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.nio.charset.Charset;
import java.util.List;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class InitVectorStore {

    private final VectorStore vectorStore;

    private final RedisTemplate<String, String> redisTemplate;

    @Value("classpath:ops.txt")
    private Resource opsFile;

    @PostConstruct
    public void init() {
        //拿取原始资源
        TextReader textReader = new TextReader(opsFile);
        textReader.setCharset(Charset.defaultCharset());


        //重复引用判断
        String fileName = (String) textReader.getCustomMetadata().get(TextReader.SOURCE_METADATA);
        String fileHash = DigestUtil.md5Hex(fileName);
        String key = "rag:source:" + fileName + ":" + fileHash;
        Boolean doCite = redisTemplate.opsForValue().setIfAbsent(key, "1");

        //保存到知识库
        if (Boolean.TRUE.equals(doCite)) {
            //文件转向量
            List<Document> documents = new TokenTextSplitter().transform(textReader.get());
            //保存到向量数据库
            vectorStore.add(documents);
        }else{
            log.info("----------重复初始化资源:{}-----------", fileName);
        }
    }
}
